package edu.xidian.sselab.cloudcourse.repository;

import edu.xidian.sselab.cloudcourse.domain.test4_entity;
import edu.xidian.sselab.cloudcourse.hbase.HbaseClient;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class test4_Repository {

    private static final String TABLE_NAME = "monthLevelSales";
    private final HbaseClient hbaseClient;

    @Autowired
    public test4_Repository(HbaseClient hbaseClient){
        this.hbaseClient = hbaseClient;
    }

    public List<test4_entity> find(String level,String start_time, String end_time) throws IOException {
        List<test4_entity> temprecords = new ArrayList<>();
        hbaseClient.getConnection();
        Table table = hbaseClient.getTableByName(TABLE_NAME);
        FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL); //交集
        RowFilter rowFilter1 = new RowFilter(
                CompareFilter.CompareOp.EQUAL,
                new RegexStringComparator("##" + level + "$"));
        filterList.addFilter(rowFilter1);
        Scan scan = new Scan();
        if (filterList.getFilters().size() != 0) {
            scan.setFilter(filterList);
        }
        ResultScanner rs;
        try {
            if (table != null) {
                rs = table.getScanner(scan);
                for (Result result : rs) {
                    test4_entity temp = new test4_entity().map(result);
                    temprecords.add(temp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("查询出错，返回一个空的列表!");
        }
        List<test4_entity> records = new ArrayList<>();
        for(test4_entity t:temprecords){
            if(t.getDatee().compareTo(start_time)>=0 && t.getDatee().compareTo(end_time)<=0)
                records.add(t);
        }
        table.close();
        hbaseClient.closeConnection();
        return records;
    }
}
